package project.simpleMsg;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.frame.LengthFieldBasedFrameDecoder;
import org.jboss.netty.handler.codec.frame.LengthFieldPrepender;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;
import org.jboss.netty.util.HashedWheelTimer;

public class SimpleMsgClient {

	private final String host;
	private final int port;
	private SimpleMsgClientHandler handler = null;
	protected static int maxFrameLength = 1024 * 1000;

	public SimpleMsgClient(String host, int port) {
		this.host = host;
		this.port = port;
	}

	public Channel bootstrap() {
		final ClientBootstrap bootstrap = new ClientBootstrap(
				new NioClientSocketChannelFactory(
						Executors.newCachedThreadPool(),
						Executors.newCachedThreadPool()));
		handler = new SimpleMsgClientHandler(bootstrap, new HashedWheelTimer());
		bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
			@Override
			public ChannelPipeline getPipeline() throws Exception {
				return Channels.pipeline( new StringEncoder(
								Charset.forName("UTF-8")), new StringDecoder(
								Charset.forName("UTF-8")), handler);
			}
		});
		bootstrap.setOption("remoteAddress", new InetSocketAddress(host, port));

		ChannelFuture future = bootstrap.connect(new InetSocketAddress(host,
				port));

		return future.isSuccess() ? future.getChannel() : null;
	}
}
